import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WindowTable extends JFrame implements ActionListener {
   JTable table;
   Object [][] a; 
   Object [] name={"姓名","英语","数学","总成绩"};
   JButton 设置表格行数,计算;
   JTextField inputNumber;
   int rows=1;
   JPanel p;
   WindowTable() {
     init();
     setSize(550,200);
     setVisible(true);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   void init() {
     计算=new JButton("总成绩");   
     设置表格行数=new JButton("确定");
     inputNumber=new JTextField(10);
     设置表格行数.addActionListener(this);
     计算.addActionListener(this);
     a=new Object[rows][4];
    
     table=new JTable(a,name);
     p=new JPanel();
     p.add(new JLabel("输入表格行数"));
     p.add(inputNumber);
     p.add(设置表格行数);
     p.add(计算);
     add(p,BorderLayout.SOUTH);
     add(new JScrollPane(table),BorderLayout.CENTER);
  
    } 
    public void actionPerformed(ActionEvent e) {
       if(e.getSource()==设置表格行数) {
           rows=Integer.parseInt(inputNumber.getText());
           a=new Object[rows][4];
           table=new JTable(a,name);
           getContentPane().removeAll();
           add(new JScrollPane(table),BorderLayout.CENTER);
           add(p,BorderLayout.SOUTH);
           validate();
       }
       else if(e.getSource()==计算) {
          for(int i=0;i<rows;i++) {
             double sum=0;
             boolean boo=true;
             for(int j=1;j<=2;j++) {
                try{ 
                   sum=sum+Double.parseDouble(a[i][j].toString());
                }
                catch(Exception ee) {
                   boo=false;
                   table.repaint();
                }
                if(boo==true) {
                   a[i][3]=""+sum;
                   table.repaint();
                }
             }
          } 
       }
    }
}
